package cn.stylefeng.guns.modular.ums.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.ums.entity.Message;
import cn.stylefeng.guns.modular.ums.mapper.MessageMapper;
import cn.stylefeng.guns.modular.ums.model.params.MessageParam;
import cn.stylefeng.guns.modular.ums.model.result.MessageResult;
import  cn.stylefeng.guns.modular.ums.service.MessageService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 消息管理表 服务实现类
 * </p>
 *
 * @author yzb
 * @since 2019-11-07
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Override
    public void add(MessageParam param){
        Message entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(MessageParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(MessageParam param){
        Message oldEntity = getOldEntity(param);
        Message newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public MessageResult findBySpec(MessageParam param){
        return null;
    }

    @Override
    public List<MessageResult> findListBySpec(MessageParam param){
        return null;
    }

    @Override
    @Transactional
    public LayuiPageInfo findPageBySpec(MessageParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        //更新消息已读状态
        List<MessageResult> list=page.getRecords();
        MessageParam param1=new MessageParam();
        for (MessageResult messageResult:list){
            ToolUtil.copyProperties(messageResult, param1);
            param1.setIfReaded(1);
            this.update(param1);
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(MessageParam param){
        return param.getFeedbackId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Message getOldEntity(MessageParam param) {
        return this.getById(getKey(param));
    }

    private Message getEntity(MessageParam param) {
        Message entity = new Message();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
